<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Company as CompanyModel;
use think\Db;
use Exception;

/**
 * 公司管理
 *
 * @icon fa fa-user
 */
class Company extends Backend
{
	protected $dataLimit = true;
    protected $searchFields = 'companyname';

    /**
     * @var \app\admin\model\Company
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Company');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
				$this->dataLimit = false;
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
				->with(['admin'])
				->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
			
            return json($result);
        }
        return $this->view->fetch();
    }
	
	/**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
		
		$this->token();
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $result = false;
        Db::startTrans();
        try {
			$params['admin_id'] = $this->auth->id;
			
			$level = 1;
			$levelnumber = $params['networkaware']+$params['hassales']+$params['localinfluence']+$params['enthusiasm']+$params['ismanufacturer']+$params['isrecommend'];
			if($levelnumber >= 6)
			{
				$level = 3;
			}
			elseif($levelnumber >= 3)
			{
				$level = 2;
			}
			$params['level'] = $level;
			$result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
		
		if($result == false)
		{
			$this->error('保存失败');
		}

        $this->success('添加成功');
    }
	
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
		
		$this->token();
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
        $result = false;
        Db::startTrans();
        try {
			$level = 1;
			$levelnumber = $params['networkaware']+$params['hassales']+$params['localinfluence']+$params['enthusiasm']+$params['ismanufacturer']+$params['isrecommend'];
			if($levelnumber >= 6)
			{
				$level = 3;
			}
			elseif($levelnumber >= 3)
			{
				$level = 2;
			}
			$params['level'] = $level;
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
	
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
		if (!$ids) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $count = $this->model->where('id', 'in', $ids)->delete();
		if ($count) {
			$this->success();
		}

        $this->error(__('No rows were deleted'));
    }
}
